home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
Tech Arsenal 1
/
Tech Arsenal (Arsenal Computer).ISO
/
tek-01
/
lcppb.zip
/
LCPPLIB.ZIP
/
STRITEM.CPP
< prev
next >
Wrap
C/C++ Source or Header
|
1991-07-04
|
3KB
|
75 lines
// stritem.cpp -- String item class
#include <string.h>
#include "error.h"
#include "stritem.h"
/* -- Constructor. Create copy of string addressed by s as a new
strItem object. Argument may be NULL. */
strItem::strItem(const char *s)
{
sp = NULL; // Initialize private data field
putString(s); // Save argument string in object
}
/* -- Alternate constructor. Creates copy of string containing up to
the number of characters specified in maxLen. Argument may be NULL.
If maxLen is 0 or less, allocate no space to string. */
strItem::strItem(const char *s, int maxLen)
{
sp = NULL; // Initialize private data field
putString(s, maxLen); // Save limited-length string
}
/* -- Destructor. Deletes space occupied by string and addressed by
sp, which may be NULL. Runs when a strItem object is deleted. Because
object is about to be deleted anyway, sp is not set to NULL. */
strItem::~strItem()
{
if (sp) delete sp; // i.e. delete if sp != NULL
}
/* -- Insert string into string object, replacing any string
now addressed. */
void strItem::putString(const char *s)
{
if (sp) delete sp; // Dispose old string (if any)
sp = NULL; // Prevent accidental use of old pointer
if (s == NULL) return; // Exit if argument is NULL
sp = strdup(s); // Copy s to new string at sp
if (sp == NULL) // Test for strdup error
error(ERRMEM); // Signal error copying string
}
/* -- Overloaded putString function. Same as putString above, but
limits the new string to maxLen characters. */
void strItem::putString(const char *s, int maxLen)
{
int len; // Length of string.
if (sp) delete sp; // Dispose old string (if any)
sp = NULL; // Prevent accidental use of old pointer
if (s == NULL) return; // Exit if argument is NULL
if (maxLen <= 0) return; // If maxLen <= 0, exit with sp==NULL
len = strlen(s); // Set len to argument string length
if (len > maxLen) // If string is longer than maxLen
len = maxLen; // limit len to maxLen
sp = new char[len + 1]; // Create space for string + NULL
if (sp == NULL) // Test whether new() found enough memory
error(ERRMEM); // If not, signal out of memory error
else {
strncpy(sp, s, len); // Else, copy len chars to sp
sp[len] = NULL; // Make sure string ends with NULL
}
}
// Copyright (c) 1990 by Tom Swan. All rights reserved
// Revision 1.00 Date: 09/23/1990 Time: 04:41 pm